package nobu.nakata.nfcfare.resource.impl;

import javax.jdo.PersistenceManager;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.resource.IBussesResource;
import nobu.nakata.nfcfare.resource.item.IBusResourceItem;
import nobu.nakata.nfcfare.resource.mapper.BusResourceMapper;
import nobu.nakata.nfcfare.resource.util.ServiceResourceUtil;

import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import com.google.appengine.api.users.User;

public class BussesResource extends ServerResource implements IBussesResource {
	
	/* (non-Javadoc)
	 * @see nobu.nakata.nfcfare.resource.ITrainsResource#create(nobu.nakata.nfcfare.resource.item.TrainResourceItem)
	 */
	@Override
	public IBusResourceItem create(IBusResourceItem newResourceItem) {
		PersistenceManager pm = null;
		try {
			User viewer = ServiceResourceUtil.getViewer();
			if (viewer == null)
				throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN);
			Cache cache = ServiceResourceUtil.makeCache();
			pm = ServiceResourceUtil.makeStorage();
			BusResourceMapper resourceMapper = new BusResourceMapper(cache, pm, viewer);
			if (resourceMapper.findByTrainStationCode(newResourceItem.getBusCode()) != null)
				throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
			resourceMapper.set(newResourceItem);
			return newResourceItem;
		} catch(ResourceException e) {
			throw e;
		} catch(Throwable th) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		} finally {
			if (pm != null)
				pm.close();
		}
	}
}
